<script setup lang="tsx">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { reactive, watch, inject, Ref, ref, onBeforeUnmount, onMounted, nextTick } from 'vue'
import {
  ElCheckboxGroup,
  ElCheckbox,
  ElInput,
  ElButton,
  ElMessage,
  ElImage,
  ElRadioGroup,
  ElDivider,
  ElRadio,
  ElForm,
  ElFormItem,
  ElPagination
} from 'element-plus'
import { getStoreApi, getBindApi, FormData } from '@/api/product/list'
import { getListApi } from '@/api/product/classification'
import { searchStoreApi } from '@/api/utils/search'
const emit = defineEmits(['close', 'get-list'])
const currentRow = inject('currentRow') as FormData
const formRef = ref<InstanceType<typeof ElForm>>()
const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods
const store_ids = ref([])
const name = ref('')
const pageSize = ref(10)
const currentPage = ref(1)
const count = ref(0)
const loading = ref(false)
const from = ref({
  is_all_channel: '',
  store_ids: []
})
onMounted(() => {
  getListApidata()
  getStoreApiData()
})
// 门店
const optionsSales = ref<Array<{ name: string; id: number; checked: boolean }>>([])
const getSalesdata = async (name) => {
  const res = await searchStoreApi({
    page: currentPage.value,
    limit: pageSize.value,
    field: 'id,name,salesman_id',
    name: name
  })
  optionsSales.value = res.data.list
  optionsSales.value.forEach((item1) => {
    const matchedItem = optionsData.value.find((item2) => item1.id === item2)
    if (matchedItem) {
      item1.checked = true
    }
  })
  count.value = res.data.count
}
// 分类
const options = ref<Array<{ name: string; id: number }>>([])
const getListApidata = async () => {
  const res = await getListApi({ field: 'id,name,pid' })
  options.value = res.data.list.map((item) => {
    return {
      label: item.name,
      value: item.id,
      children: item.children.map((child) => {
        return {
          label: child.name,
          value: child.id
        }
      })
    }
  })
}
const optionsData = ref([])

const getStoreApiData = async () => {
  const res = await getStoreApi({ company_goods_id: currentRow.id })
  const list = res.data.list
  optionsData.value = list
  getSalesdata('')
  from.value.is_all_channel = res.data.is_all_channel.toString()
}
const search = () => {
  if (name.value) {
    getSalesdata(name.value)
  } else {
    ElMessage('请输入搜索内容')
  }
}
const Reset = () => {
  getSalesdata('')
  name.value = ''
}
const schema = reactive<FormSchema[]>([
  {
    field: '',
    label: '基础信息',
    component: 'Divider',
    colProps: { span: 28 }
  },
  {
    field: 'name',
    label: '商品名称',
    component: 'Input'
  },
  {
    field: 'goods_cate_id_two',
    label: '商品分类',
    component: 'TreeSelect',
    componentProps: {
      renderAfterExpand: false,
      data: options
    }
  },
  {
    field: 'unit',
    label: '商品单位',
    component: 'Input'
  },
  {
    field: 'shelf_life',
    label: '保质期(天)',
    component: 'Input'
  },
  {
    field: 'img',
    label: '商品图片',
    formItemProps: {
      slots: {
        default: ({ img }) => {
          return img ? (
            <div class="custom-label">
              {img.map((src, index) => (
                <ElImage key={index} src={src} class="w-100px h-100px ml-10px" />
              ))}
            </div>
          ) : null
        }
      }
    }
  },
  {
    field: '',
    label: '',
    component: 'Divider',
    colProps: { span: 28 }
  }
])

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    const formDataList = {
      id: formData.id || '',
      real_name: formData.real_name || '',
      mobile: formData.mobile || '',
      money: formData.amount || '',
      type: formData.type || '',
      store_ids: store_ids.value.join(',') || ''
    }
    return formDataList
  }
}

const reset = async () => {
  const elForm = await getElFormExpose()
  elForm?.resetFields()
}
const handleRadioChange = (value) => {
  from.value.is_all_channel = value
}
// 分页
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  getSalesdata('')
}

// 提交
const save = async () => {
  loading.value = true
  const formData = {
    company_goods_id: currentRow.id,
    is_all_channel: from.value.is_all_channel,
    store_ids: from.value.store_ids.join(',')
  }
  const res = await getBindApi(formData)
  if (res) {
    loading.value = false
    ElMessage.success(res.msg)
    reset()
    emit('close')
    emit('get-list')
  } else {
    loading.value = false
  }
}
watch(
  () => currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

onBeforeUnmount(reset)

defineExpose({
  submit,
  reset
})
</script>

<template>
  <ContentDetailWrap title="商品权限设置">
    <Form @register="formRegister" :schema="schema" />
    <ElForm ref="formRef" :model="from">
      <ElDivider borderStyle="none" contentPosition="left">编辑购买权限</ElDivider>
      <ElFormItem prop="is_all_channel" label="是否全部渠道可见" required>
        <ElRadioGroup v-model="from.is_all_channel" @change="handleRadioChange">
          <ElRadio label="1">是</ElRadio>
          <ElRadio label="2">否</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
      <div v-if="from.is_all_channel == '2'">
        <div style="display: inline-block; margin-right: 20px">选择可见渠道:</div>
        <div style="display: inline-block; margin-right: 20px"
          ><ElInput v-model="name" style="width: 240px" placeholder="请输入"
        /></div>
        <div style="display: inline-block; margin-right: 20px"
          ><ElButton type="primary" @click="search">搜索</ElButton></div
        >
        <div style="display: inline-block"><ElButton @click="Reset">重置</ElButton></div>
      </div>
      <div
        style="width: 300px; margin-left: 100px; margin-top: 10px"
        v-if="from.is_all_channel == '2'"
      >
        <ElFormItem prop="store_ids" label="">
          <ElCheckboxGroup v-model="from.store_ids">
            <ElCheckbox
              v-for="res in optionsSales"
              :key="res.id"
              :label="res.id"
              :value="res.id"
              :checked="res.checked"
            >
              {{ res.name }}
            </ElCheckbox>
          </ElCheckboxGroup>
        </ElFormItem>
        <ElPagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="count"
          style="margin-top: 20px"
        />
      </div>
    </ElForm>
    <template #footer>
      <div class="w-full flex items-center justify-center">
        <BaseButton type="primary" :loading="loading" @click="save">保存</BaseButton>
        <BaseButton @click="emit('close')">取消</BaseButton>
      </div>
    </template>
  </ContentDetailWrap>
</template>
